from typing import List
from starlette.websockets import WebSocket


class WebSocketConnectionManager:
    def __init__(self):
        self.activate_connections: List[WebSocket] = list()
        self.user_connections = dict()

    async def connect(self, websocket: WebSocket, user_id: str):
        self.activate_connections.append(websocket)
        self.user_connections[user_id] = websocket

    async def disconnect(self, user_id: str):
        websocket = self.user_connections.get(user_id)
        try:
            if websocket:
                await websocket.close()
        except Exception as e:
            _ = e
        if websocket and websocket in self.activate_connections:
            self.activate_connections.remove(websocket)
        if user_id in self.user_connections:
            del self.user_connections[user_id]

    async def send_personal_message(self, message: str, user_id: str):
        websocket = self.user_connections.get(user_id)
        if websocket:
            try:
                await websocket.send_text(message)
            except Exception as e:
                print("send_personal_message ERROR:", e)

    async def broadcast(self, message: str):
        for connection in self.activate_connections:
            try:
                await connection.send_text(message)
            except Exception as e:
                print("broadcast ERROR:", e)


ws_manager = WebSocketConnectionManager()